package com.smarth.zhizulian.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventActivity;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.bean.user.MineUserInfo;
import com.smarth.zhizulian.enums.Profession;
import com.smarth.zhizulian.enums.Sex;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observable.QiNiuObservable;
import com.smarth.zhizulian.http.observer.bad.BadPageObserver;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.utils.DialogUtils;
import com.smarth.zhizulian.utils.GlideUtils;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.ShareUtils;
import com.smarth.zhizulian.utils.TimeUtils;
import com.smarth.zhizulian.utils.UserUtils;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.adapter.PageDataAdapter;
import com.smarth.zhizulian.utils.listhelper.impl.model.HttpPageDataModel;
import com.smarth.zhizulian.view.LoadingLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 18865 on 2017/12/22.
 */

public class PersonalInfoActivity extends EventActivity {
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_profession)
    TextView tvProfession;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.rl_wechat)
    RelativeLayout rlWechat;
    @BindView(R.id.iv_wechat_arrow)
    ImageView ivWechatArrow;
    private RefreshHelper<MineUserInfo> refreshHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personalinfo);
        ButterKnife.bind(this);
        setTitlebar("个人资料", true);
        init();
//        fetchUser();
    }

    private void init() {
        refreshHelper = new RefreshHelper(mContext, llLoadinglayout, null);
        refreshHelper.setDataModel(new HttpPageDataModel<MineUserInfo>(mContext) {
            @Override
            public Observable<MineUserInfo> getObservable() {
                return KumaHttp.getService().mineUserInfo()
                        .compose(RxCompos.<MineUserInfo>getBELoginCompos());
            }
        });
        refreshHelper.setDataAdapter(new PageDataAdapter<MineUserInfo>() {
            @Override
            public void onGetData(MineUserInfo mineUserInfo, boolean isRefresh) {
                super.onGetData(mineUserInfo, isRefresh);
                GlideUtils.loadAvatar(mContext, mineUserInfo.getAvatar(), ivAvatar);
                tvName.setText(mineUserInfo.getNickname());
                tvSex.setText(Sex.getName(mineUserInfo.getSex()));
                tvBirthday.setText(mineUserInfo.getBirth());
                tvProfession.setText(Profession.getName(mineUserInfo.getProfession()));
                tvPhone.setText(mineUserInfo.getPhone());
//                        tvWechat.setText(mineUserInfo.getWechat());
                if (!TextUtils.isEmpty(mineUserInfo.getWechat())) {
                    rlWechat.setClickable(false);
                    tvWechat.setText("已绑定");
                    ivWechatArrow.setVisibility(View.INVISIBLE);
                } else {
                    rlWechat.setClickable(true);
                    tvWechat.setText("未绑定");
                    ivWechatArrow.setVisibility(View.VISIBLE);
                }
            }
        });
        refreshHelper.refresh();
    }

    public static void open(Context context) {
        if (!UserUtils.isLogin()) {
            LoginActivity.open(context);
            return;
        }
        Intent i = new Intent(context, PersonalInfoActivity.class);
        context.startActivity(i);
    }

    @Subscriber(tag = BaseConfig.EventTag.ON_EDIT)
    private void onEdit(EventBean eb) {
        refreshHelper.loadMore();
    }

    @OnClick({R.id.rl_name, R.id.rl_sex, R.id.rl_birthday, R.id.rl_profession, R.id.rl_phone, R.id.rl_wechat, R.id.iv_avatar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_name:
                EditActivity.open(mContext, "修改昵称", EditActivity.MODE_NAME, tvName.getText().toString());
                break;
            case R.id.rl_sex:
                //条件选择器
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
//                        //返回的分别是三个级别的选中位置
//                        String tx = options1Items.get(options1).getPickerViewText()
//                                + options2Items.get(options1).get(option2)
//                                + options3Items.get(options1).get(option2).get(options3).getPickerViewText();
//                        tvOptions.setText(tx);
                        Map<String, Object> map = new HashMap<>();
                        map.put("sex", options1);
                        KumaHttp.getService().mineEditUserInfo(map)
                                .compose(RxCompos.getBEAllLoginCompos())
                                .subscribe(new ProgressObserver<BaseEntity<Object>>(mContext) {
                                    @Override
                                    public void onNext(BaseEntity<Object> objectBaseEntity) {
                                        EventBus.getDefault().post(new EventBean(), BaseConfig.EventTag.ON_EDIT);
                                    }
                                });
                    }
                }).build();
                pvOptions.setPicker(Arrays.asList(Sex.values()));
                pvOptions.show();
                break;
            case R.id.rl_birthday:
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        Map<String, Object> map = new HashMap<>();
                        map.put("birth", TimeUtils.format(date));
                        KumaHttp.getService().mineEditUserInfo(map)
                                .compose(RxCompos.getBEAllLoginCompos())
                                .subscribe(new ProgressObserver<BaseEntity<Object>>(mContext) {
                                    @Override
                                    public void onNext(BaseEntity<Object> o) {
                                        EventBus.getDefault().post(new EventBean(), BaseConfig.EventTag.ON_EDIT);
                                    }
                                });
                    }
                }).setType(new boolean[]{true, true, true, false, false, false}).build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.rl_profession:
                OptionsPickerView pv2 = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
//                        //返回的分别是三个级别的选中位置
//                        String tx = options1Items.get(options1).getPickerViewText()
//                                + options2Items.get(options1).get(option2)
//                                + options3Items.get(options1).get(option2).get(options3).getPickerViewText();
//                        tvOptions.setText(tx);
                        Map<String, Object> map = new HashMap<>();
                        map.put("profession", options1);
                        KumaHttp.getService().mineEditUserInfo(map)
                                .compose(RxCompos.getBEAllLoginCompos())
                                .subscribe(new ProgressObserver<BaseEntity<Object>>(mContext) {
                                    @Override
                                    public void onNext(BaseEntity<Object> o) {
                                        EventBus.getDefault().post(new EventBean(), BaseConfig.EventTag.ON_EDIT);
                                    }
                                });
                    }
                }).build();
                pv2.setPicker(Arrays.asList(Profession.values()));
                pv2.show();
                break;
            case R.id.rl_phone:
                break;
            case R.id.rl_wechat:
//                EditActivity.open(mContext, "修改微信号", EditActivity.MODE_WECHAT, tvWechat.getText().toString());
                DialogUtils.showNetWorkAccess(mContext);
                ShareUtils.thirdLogin(ShareSDK.getPlatform(Wechat.NAME), new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                        DialogUtils.closeProgressDialog();
                        fetchUploadWechat((String) hashMap.get("openid"));
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        throwable.printStackTrace();
                        DialogUtils.closeProgressDialog();
                        KumaToast.show(mContext, "授权失败");
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        DialogUtils.closeProgressDialog();
                        KumaToast.show(mContext, "授权取消");
                    }
                });
                break;
            case R.id.iv_avatar:
//                MultiImageSelector.create(mContext)
//                        .single()
//                        .showCamera(true)
//                        .start(mContext, REQUEST_IMAGE);
                new RxPermissions(mContext)
                        .request(Manifest.permission.CAMERA
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE

                        )
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    PictureSelector.create(mContext)
                                            .openGallery(PictureMimeType.ofImage())
                                            .selectionMode(PictureConfig.SINGLE)
                                            .enableCrop(true)
                                            .withAspectRatio(1, 1)
                                            .forResult(PictureConfig.CHOOSE_REQUEST);
                                } else {
                                    KumaToast.show(mContext, "请开通权限后重试");
                                }
                            }
                        });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    final LocalMedia m = selectList.get(0);
//                    KumaToast.show(mContext, "" + m.getCutPath());
                    KumaHttp.getService().qiniuGetToken()
                            .compose(RxCompos.<String>getBELoginCompos())
                            .flatMap(new Function<String, ObservableSource<String>>() {
                                @Override
                                public ObservableSource<String> apply(String s) throws Exception {
                                    return new QiNiuObservable(m.getCutPath(), "image/a_" + UUID.randomUUID().toString(), s);
                                }
                            })
                            .subscribeOn(Schedulers.io())
                            .observeOn(Schedulers.io())
                            .flatMap(new Function<String, ObservableSource<BaseEntity<Object>>>() {
                                @Override
                                public ObservableSource<BaseEntity<Object>> apply(String s) throws Exception {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("avatar", s);
                                    return KumaHttp.getService().mineEditUserInfo(map);
                                }
                            })
                            .compose(RxCompos.getBEAllLoginCompos())
                            .subscribe(new ProgressObserver<BaseEntity<Object>>(mContext) {
                                @Override
                                public void onNext(BaseEntity<Object> o) {
                                    KumaToast.show(mContext, "上传成功！");
                                    EventBus.getDefault().post(new EventBean(), BaseConfig.EventTag.ON_EDIT);
                                }
                            });

                    break;
            }
        }
    }

    private void fetchUploadWechat(String wechat) {
        Map<String, Object> map = new HashMap<>();
        map.put("wechat", wechat);
        KumaHttp.getService().mineEditUserInfo(map)
                .compose(RxCompos.getBEAllLoginCompos())
                .subscribe(new ProgressObserver<BaseEntity<Object>>(mContext) {
                    @Override
                    public void onNext(BaseEntity<Object> o) {
                        EventBus.getDefault().post(new EventBean(), BaseConfig.EventTag.ON_EDIT);
                    }
                });
    }
}
